import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'
console.log('vue3子应用路由')
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (About.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import('../views/AboutView.vue')
  }
]

const modules: Record<string, { default: Array<RouteRecordRaw> }> = import.meta.glob(
  './modules/*.ts',
  { eager: true }
) as Record<string, { default: Array<RouteRecordRaw> }> // 获取所有模块
console.log('🚀 ~ modules:', modules)

// 使用 Promise.all 来确保所有模块都加载完毕
// const loadModules = async () => {
//   const modulePromises = Object.values(modules).map((module) => module())
//   const moduleResults = await Promise.all(modulePromises)

//   moduleResults.forEach((mod) => {
//     console.log('🚀 ~ mod:', mod.default) // 可以访问每个模块的内容
//     routes.push(...mod.default)
//     mod.default.forEach((route) => {
//       router.addRoute(route)
//     })
//   })
//   console.log('最后组合的路由', routes)
// }
const loadModules = () => {
  const routeArray = Object.entries(modules).map(([path, module]) => {
    return {
      path: path.replace('./src/routes', '').replace('.js', ''), // 处理路径
      module // 模块
    }
  })
  const asyRouter = routeArray.map((route) => {
    return {
      ...route,
      routersInfo: route.module.default
    }
  })

  asyRouter.forEach((route) => {
    const routersInfo = route.routersInfo
    console.log('🚀 ~ routersInfo ~ routersInfo:', routersInfo)
    // routes.push(...routersInfo)
    routersInfo.forEach((route) => {
      routes.push(route)
    })
  })
}
console.log('路由加载完成', routes)
loadModules()
console.log('路由加载后面', routes)

const router = createRouter({
  history: createWebHistory(
    qiankunWindow.__POWERED_BY_QIANKUN__ ? '/vue3Subapp' : import.meta.env.BASE_URL
  ),
  routes
})

export default router

// // 需要时使用：
// for (const path in modules) {
//   modules[path]().then((mod) => {
//     console.log('🚀 ~ modules[path] ~ mod:', mod.default) // 可以访问每个模块的内容
//     routes.push(...mod.default)
//   })
// }
// console.log('最后组合的路由', routes)

// const router = createRouter({
//   history: createWebHistory(
//     // '/vue3Subapp'
//     qiankunWindow.__POWERED_BY_QIANKUN__ ? '/vue3Subapp' : import.meta.env.BASE_URL
//   ),
//   routes
// })

// export default router
